package com.boco.pciv.controller.project;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.boco.pciv.SysProperties;
import com.boco.pciv.controller.PcivController;
import com.boco.pciv.controller.company.CompanyController;
import com.boco.pciv.core.entity.*;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.entity.project.*;
import com.boco.pciv.service.banzu.IBanzuService;
import com.boco.pciv.service.company.ICompanyService;
import com.boco.pciv.service.project.IProjectCheckService;
import com.boco.pciv.service.project.IProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by sunrise on 2020/7/16.
 */
@RestController
@RequestMapping(value="/project/")
public class ProjectController extends PcivController {
    Logger logger = LoggerFactory.getLogger(CompanyController.class);

    @Resource
    private IBanzuService iBanzuService;
    @Resource
    private IProjectService iProjectService;
    @Resource
    private IProjectCheckService iProjectCheckService;
    @Resource
    private ICompanyService iCompanyService;
    @Autowired
    SysProperties sysConfig;

    /**
     * 列表
     */
    @GetMapping("/list")
    public PageResultBase list(String projectName, String companyName,String projectstatus, String op, LayUIPager pager) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(projectName)) {
            param.putCriteria("projectName", projectName);
        }
        if (StrUtil.isNotBlank(companyName)) {
            param.putCriteria("companyName", companyName);
        }
        if (StrUtil.isNotBlank(projectstatus)) {
            param.putCriteria("proStatus", projectstatus);
        }
        LoginUser user=getCurUser();
        if(user.getUserType()!=0){
            param.putCriteria("licno", user.getDeptId());
        }
        param.putCriteria("userType", user.getUserType());
        if (op != "1") {
            param.putCriteria("status", op);
        }
        //其他查询条件
        PageResultBase result = iProjectService.getPage(param);
        return result;
    }

    @GetMapping("/banzulist")
    public PageResultBase banzulist(String banzuname, String companyName, String projectname, LayUIPager pager) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(banzuname)) {
            param.putCriteria("banzu_name", banzuname);
        }
        if (StrUtil.isNotBlank(companyName)) {
            param.putCriteria("companyName", companyName);
        }
        if (StrUtil.isNotBlank(projectname)) {
            param.putCriteria("projectname", StrUtil.format("('{}')",projectname.replaceAll(",","','")));
        }
        LoginUser user = getCurUser();
        if(user.getUserType()!=0){
            param.putCriteria("licno",user.getDeptId());
        }
        PageResultBase result = iProjectService.banzulist(param);
        return result;
    }

    @GetMapping("/checklist")
    public PageResultBase checklist(String projectName, String companyName, String op, LayUIPager pager) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(projectName)) {
            param.putCriteria("projectName", projectName);
        }
        if (StrUtil.isNotBlank(companyName)) {
            param.putCriteria("companyName", companyName);
        }
        if (op != "1") {
            param.putCriteria("status", op);
        }
        //其他查询条件
        PageResultBase result = iProjectCheckService.getPage(param);
        return result;
    }

    /**
     * 信息
     */
    @GetMapping("/info")
    public BizResponse info(String projectId, String op) {
        if (op != null && op.equals("1")) {
            ProjectInfo info = iProjectCheckService.getProject(projectId);
            return BizResponseUtil.single(info);
        } else {
            ProjectInfo info = iProjectService.getProject(projectId);
            return BizResponseUtil.single(info);
        }
    }

    /**
     * 下拉框
     */
    @GetMapping("/getSelectByProject")
    public BizResponse getSelectByProject(String ddtype) {
        List<SelectItem> list = new ArrayList<SelectItem>();
        LoginUser user = getCurUser();
        List<ProjectInfo> result = new ArrayList<ProjectInfo>();
        if(user.getUserType()!=0){
            result = iProjectService.getSelectByProject(user.getDeptId());
        }
        else{
            result = iProjectService.getSelectByProject("");
        }
        list.add(new SelectItem("", "请选择", ddtype));
        for (ProjectInfo dd : result) {
            if("project_company".equals(ddtype)&&user.getUserType()!=0){
                if(dd.getLicno()!=null&&dd.getLicno().contains(user.getDeptId()))
                list.add(new SelectItem(dd.getProjectid(), dd.getProjectname(), ddtype));
            }
            else{
                list.add(new SelectItem(dd.getProjectid(), dd.getProjectname(), ddtype));
            }
        }
        return BizResponseUtil.list(list);
    }

    /**
     * 下拉框
     */
    @GetMapping("/getSelectByProjecttype")
    public BizResponse getSelectByProjecttype(String ddtype) {
        //下拉框
        List<SelectItem> list = new ArrayList<SelectItem>();
        List<ProjectInfo> result = new ArrayList<ProjectInfo>();
        result = iProjectService.getSelectByProjecttype();
        list.add(new SelectItem("", "请选择", ddtype));
        for (ProjectInfo dd : result) {
            list.add(new SelectItem(dd.getProjecttype(), dd.getProjecttype(), ddtype));
        }
        return BizResponseUtil.list(list);
    }

    /**
     * 下拉框
     */
    @GetMapping("/getSelectByProjectstatus")
    public BizResponse getSelectByProjectstatus(String ddtype) {
        //下拉框
        List<SelectItem> list = new ArrayList<SelectItem>();
        List<ProjectInfo> result = new ArrayList<ProjectInfo>();
        result = iProjectService.getSelectByProjectstatus();
        list.add(new SelectItem("", "请选择", ddtype));
        for (ProjectInfo dd : result) {
            list.add(new SelectItem(dd.getProjecttype(), dd.getProjecttype(), ddtype));
        }
        return BizResponseUtil.list(list);
    }

    /**
     * 下拉框
     */
    @GetMapping("/getyear")
    public BizResponse getyear(String ddtype) {
        //下拉框
        Integer year = Integer.parseInt(DateUtil.format(DateUtil.date(), "yyyy"));
        List<SelectItem> list = new ArrayList<SelectItem>();
        list.add(new SelectItem("", "请选择", ddtype));
        for (int i = 0; i < 15; i++) {
            list.add(new SelectItem(String.valueOf((year - i)), String.valueOf((year - i)), ddtype));
        }
        return BizResponseUtil.list(list);
    }

    /**
     * 保存
     */
    @PostMapping("/add")
    public BizResponse add(String json, String op) {
        try {
            ProjectInfo info = JSONUtil.toBean(json, ProjectInfo.class);
            if (logger.isDebugEnabled()) {
                logger.debug("add data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            info.setProjectid(RandomUtil.randomNumbers(4) + "-" + RandomUtil.randomNumbers(3));
            info.setCreateUser(getCurUserId());
            //验证项目唯一性
            int number = iProjectCheckService.CheckProject(info);
            if (number > 0) {
                return BizResponseUtil.fail("当前项目名称已存在!");
            }
            if (op.equals("1")) {
//                iProjectService.addProject(info);
                info.setStatus("2");
                iProjectService.addProject(info);
            } else {
                info.setStatus("1");
//                iProjectService.addProject(info);
                iProjectCheckService.addProject(info);
            }
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 修改
     */
    @PostMapping("/edit")
    public BizResponse update(String json, String op) {
        try {
            ProjectInfo info = JSONUtil.toBean(json, ProjectInfo.class);
            if (info == null) {
                return BizResponseUtil.fail("修改信息不能为空");
            }
            info.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            info.setUpdateUser(getCurUserId());
            if (op.equals("1")) {
                info.setStatus("2");
                iProjectService.editProject(info);
            } else {
                info.setStatus("1");
                iProjectCheckService.editProject(info);
            }
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    private boolean CheckManage() {
        User param = new User();
        param.setDept(getCurUserId());
        User tem = iProjectCheckService.getDept(param);
        String user = sysConfig.getManageDept();
        String[] list = user.split(",");
        for (String dd : list) {
            if (dd.equals(tem.getDept())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BizResponse delete(String projectId, String status) {
        try {
//            iProjectService.deleteProject(projectId);
            iProjectService.deleteProject(projectId, status);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }


    @PostMapping("/upstatus")
    public BizResponse upstatus(String projectId, Integer status, String reason) {
        try {
            if (StrUtil.isBlank(projectId)) {
                return BizResponseUtil.fail("项目ID 为空");
            }
            if (status == null) {
                return BizResponseUtil.fail("状态 为空");
            }
            if (status == 3 && StrUtil.isBlank(reason)) {
                return BizResponseUtil.fail("原因 为空");
            }
            ProjectInfo info = iProjectCheckService.getProject(projectId);
//            info.setUpdateUser(getCurUserId());
//            info.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            if (status == 2) {
                ProjectInfo pro = iProjectService.getProject(projectId);
                if (pro != null) {
                    iProjectService.editProject(info);
                } else {
                    iProjectService.addProject(info);
                }
            }
            ProjectInfo projectInfo = new ProjectInfo();
            projectInfo.setProjectname(info.getProjectname());
            projectInfo.setCompanyname(info.getCompanyname());
            projectInfo.setProjectid(projectId);
            projectInfo.setStatus(status.toString());
            if (reason == null) {
                projectInfo.setReason("");
            } else {
                projectInfo.setReason(reason);
            }
            projectInfo.setUpdateUser(getCurUserId());
            projectInfo.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iProjectCheckService.editProject(projectInfo);
            //记录
            iProjectCheckService.insertRecord(projectInfo);
//            iRecordService.projectRecord(info, status, getCurUserId());
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }


    /**
     * 班组保存
     */
    @PostMapping("/banzuadd")
    public BizResponse banzuadd(String json) {
        try {
            banzuinfo info = JSONUtil.toBean(json, banzuinfo.class);
            if (logger.isDebugEnabled()) {
                logger.debug("banzuadd data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            LoginUser user = getCurUser();
            Map<String, Object> map = new HashMap();
            map.put("licNo", user.getDeptId());
            List<CompanyInfo> result = iCompanyService.queryList(map);
            if (result.size() > 0) {
                info.setBanzu_name(info.getProjectname() + "_" + result.get(0).getName() + "_" + info.getProfession_name());
            } else {
                info.setBanzu_name(info.getProjectname() + "__" + info.getProfession_name());
            }
            info.setLicno(user.getDeptId());
            info.setCreateUser(user.getUserId());
            iProjectService.banzuadd(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 所属公司信息信息
     */
    @GetMapping("/pro_com_name")
    public BizResponse pro_com_name() {
        LoginUser user = getCurUser();
        SearchCriteria param=new SearchCriteria();
        param.setIsPage(false);
        param.putCriteria("userId",user.getUserId());
        param.putCriteria("userType",user.getUserType());
        String info = iProjectService.pro_com_name(param);
        return BizResponseUtil.single(info);
    }

    /**
     * 班组信息
     */
    @GetMapping("/banzuinfo")
    public BizResponse banzuinfo(String Id) {
        LoginUser user = getCurUser();
        if (StrUtil.isBlank(Id)) {
            Id = user.getPhone();
        }
        banzuinfo info = iProjectService.getBanzuProject(Id);
        return BizResponseUtil.single(info);
    }

    /**
     * 班组修改
     */
    @PostMapping("/banzuedit")
    public BizResponse banzuedit(String json) {
        try {
            banzuinfo info = JSONUtil.toBean(json, banzuinfo.class);
            if (info == null) {
                return BizResponseUtil.fail("修改信息不能为空");
            }
            String[] names = info.getBanzu_name().split("_");
            info.setBanzu_name(names[0] + "_" + names[1] + "_" + info.getProfession_name());
            info.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            info.setUpdateUser(getCurUserId());
            iProjectService.editbanzu(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 班组删除
     */
    @PostMapping("/deletebanzu")
    public BizResponse deletebanzu(String id, String status) {
        try {
//            iProjectService.deleteProject(projectId);
            iProjectService.deletebanzu(id, status);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 班组工资填报
     */
    @PostMapping("/banzuSend")
    public BizResponse banzuSend(String json) {
        try {
            banzuinfo info = JSONUtil.toBean(json, banzuinfo.class);
            if (logger.isDebugEnabled()) {
                logger.debug("banzuadd data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            LoginUser user = getCurUser();
            info.setLicno(user.getDeptId());
            info.setCreateUser(user.getUserId());
            String str=iProjectService.banzuSend(info);
            if(StrUtil.isNotBlank(str)){
                return  BizResponseUtil.fail(str);
            }
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    @GetMapping("/banzusendlist")
    public PageResultBase banzusendlist(LayUIPager pager, String banzuname, String companyName, String op,String sdate,String edate) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(banzuname)) {
            param.putCriteria("banzu_name", banzuname);
        }
        if (StrUtil.isNotBlank(companyName)) {
            param.putCriteria("companyName", companyName);
        }
        if (StrUtil.isNotBlank(sdate)) {
            param.putCriteria("sdate", sdate);
        }
        if (StrUtil.isNotBlank(edate)) {
            param.putCriteria("edate", edate);
        }
        LoginUser user = getCurUser();
        if(user.getUserType()!=0)
        param.putCriteria("licno", user.getDeptId());
        //其他查询条件
//        PageResultBase result = iBanzuService.getPage(param);
        PageResultBase result = iProjectService.banzusendlist(param);

        return result;
    }

    /**
     * 班组工资上报删除
     */
    @PostMapping("/deletebanzusend")
    public BizResponse deletebanzusend(String id) {
        try {
            iProjectService.deletebanzusend(id);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 上报信息
     */
    @GetMapping("/sendinfo")
    public BizResponse sendinfo(String Id) {
        banzuinfo info = iProjectService.sendinfo(Id);
        return BizResponseUtil.single(info);
    }

    @PostMapping("/upsendstatus")
    public BizResponse upsendstatus(String Id, Integer status, String reason) {
        try {
            if (StrUtil.isBlank(Id)) {
                return BizResponseUtil.fail("项目ID 为空");
            }
            if (status == null) {
                return BizResponseUtil.fail("状态 为空");
            }
            if (status == 3 && StrUtil.isBlank(reason)) {
                return BizResponseUtil.fail("原因 为空");
            }
            banzuinfo Info = new banzuinfo();
            Info.setId(Id);
            Info.setStatus(status.toString());
            if (reason == null) {
                Info.setReason("");
            } else {
                Info.setReason(reason);
            }
            Info.setUpdateUser(getCurUserId());
            Info.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iProjectService.upsendstatus(Info);
            //记录
//            iProjectCheckService.insertRecord(projectInfo);
//            iRecordService.projectRecord(info, status, getCurUserId());
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    /**
     * 民工信息保存
     */
    @PostMapping("/addPerson")
    public BizResponse addPerson(String json) {
        try {
            PersonInfo info = JSONUtil.toBean(json, PersonInfo.class);
            if (logger.isDebugEnabled()) {
                logger.debug("addPerson data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            LoginUser user = getCurUser();
            info.setCreate_user(user.getUserId());
            if(user.getUserType()!=0){
                info.setLicno(user.getDeptId());
            }
            else{
                info.setLicno("");
            }
            info.setInsert_time(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iProjectService.addPerson(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 民工信息修改
     */
    @PostMapping("/personEdit")
    public BizResponse personEdit(String json) {
        try {
            PersonInfo info = JSONUtil.toBean(json, PersonInfo.class);
            if (logger.isDebugEnabled()) {
                logger.debug("personEdit data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            info.setUpdate_user(getCurUserId());
            info.setUpdate_time(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iProjectService.personEdit(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 民工信息删除
     */
    @PostMapping("/deletePerson")
    public BizResponse deletePerson(String id) {
        try {
            iProjectService.deletePerson(id);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    /**
     * 民工查询
     */
    @GetMapping("/personlist")
    public PageResultBase personlist(LayUIPager pager, String name, String number) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(name)) {
            param.putCriteria("name", name);
        }
        if (StrUtil.isNotBlank(number)) {
            param.putCriteria("number", number);
        }
        LoginUser user = getCurUser();
        if(user.getUserType()!=0){
            param.putCriteria("licno", user.getDeptId());
        }

        //其他查询条件
        PageResultBase result = iProjectService.personlist(param);
        return result;
    }


    /**
     * 民工信息
     */
    @GetMapping("/personInfo")
    public BizResponse personInfo(String Id) {

        PersonInfo info = iProjectService.personInfo(Id);
        return BizResponseUtil.single(info);
    }

    /**
     * 民工信息下拉框
     */
    @GetMapping(value = "/getperson")
    public BizResponse getperson() {
        LoginUser user = getCurUser();
        //下拉框
        List<SelectItem> list = new ArrayList<SelectItem>();
        String companyid="";
        if(user.getUserType()!=0){
            companyid=user.getDeptId();
        }
        List<PersonInfo> result = iProjectService.getperson(companyid);
        for (PersonInfo dd : result) {
            list.add(new SelectItem(dd.getId(), dd.getName()+"("+dd.getNumber()+")", "number"));
        }
        return BizResponseUtil.list(list);
    }
    /**
     * 员工工资下发
     * */
    @PostMapping(value = "/addPersonPay")
    public BizResponse addPersonPay(String json) {
        try {
            PersonPay info = JSONUtil.toBean(json, PersonPay.class);
            if (logger.isDebugEnabled()) {
                logger.debug("addPersonPay data:{}", JSONUtil.toJsonStr(info));
            }
            if (info == null) {
                return BizResponseUtil.fail("新增信息不能为空");
            }
            LoginUser user = getCurUser();
            info.setLicno(user.getDeptId());
            iProjectService.addPersonPay(info);
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

}
